<template>
  <el-dialog
    :title="!dataForm.id ? '新建' : '编辑'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    class="SHZY-dialog SHZY-dialog_center"
    lock-scroll
  >
    <el-row :gutter="15" class="">
      <el-form
        ref="elForm"
        :model="dataForm"
        size="small"
        label-width="110px"
        label-position="right"
        :rules="rules"
      >
        <!--<el-col :span="24">
                    <el-form-item label-width="0">
                        <groupTitle content-position="left" content="抽样方案"></groupTitle>
                    </el-form-item>
                </el-col>-->
        <el-col :span="18">
          <el-form-item label="抽样方案名称" prop="name">
            <el-input
              v-model="dataForm.name"
              placeholder="请输入"
              maxlength="200"
              show-word-limit
              clearable
              required
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="有效标志" prop="enabledMark">
            <el-switch
              v-model="dataForm.enabledMark"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
          </el-form-item>
        </el-col>

        <!-- <el-col :span="24">
                    <el-form-item label-width="0">
                        <groupTitle content-position="left" content="抽样规则"></groupTitle>
                    </el-form-item>
                </el-col> -->
        <el-col :span="24">
          <el-form-item label-width="0">
            <div class="SHZY-common-title">
              <h2>抽样规则</h2>
            </div>
            <el-table
              :data="dataForm.qmsBaseSamplingplandetailList"
              size="mini"
            >
              <el-table-column
                type="index"
                width="50"
                label="序号"
                align="center"
              />
              <el-table-column prop="lowerLimit" label="批量下限">
                <template slot="header">
                  <span class="required-sign">*</span>批量下限
                </template>
                <template slot-scope="scope">
                  <!--@change="change_LowerLimit(scope.$index, scope.row)"    @blur="checkRule()"-->
                  <el-input
                    v-model="scope.row.lowerLimit"
                    :style="{ width: '100%' }"
                    placeholder="请输入"
                    clearable
                    required
                  >
                  </el-input>
                  <!--<div class="el-form-item__error">
                                        请输入规则编码
                                    </div>-->
                </template>
              </el-table-column>
              <el-table-column prop="upperLimit" label="批量上限">
                <template slot="header">
                  <span class="required-sign">*</span>批量上限
                </template>
                <template slot-scope="scope">
                  <!--@change="change_UpperLimit(scope.$index, scope.row)"-->
                  <el-input
                    v-model="scope.row.upperLimit"
                    :style="{ width: '100%' }"
                    placeholder="请输入"
                    clearable
                    required
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column prop="sampleQty" label="样本数量">
                <template slot="header">
                  <span class="required-sign">*</span>样本数量
                </template>
                <template slot-scope="scope">
                  <!--@change="change_SampleQty(scope.$index, scope.row)"-->
                  <el-input
                    v-model="scope.row.sampleQty"
                    :style="{ width: '100%' }"
                    placeholder="请输入"
                    clearable
                    required
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column prop="receivedQty" label="接收数">
                <template slot="header">
                  <span class="required-sign">*</span>接收数
                </template>
                <template slot-scope="scope">
                  <!--@change="change_ReceivedQty(scope.$index, scope.row)"-->
                  <el-input
                    v-model="scope.row.receivedQty"
                    :style="{ width: '100%' }"
                    placeholder="请输入"
                    clearable
                    required
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column prop="rejectionQty" label="拒收数">
                <template slot="header">
                  <span class="required-sign">*</span>拒收数
                </template>
                <template slot-scope="scope">
                  <!--@change="change_RejectionQty(scope.$index, scope.row)"-->
                  <el-input
                    v-model="scope.row.rejectionQty"
                    :style="{ width: '100%' }"
                    placeholder="请输入"
                    clearable
                    required
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column prop="enabledMark" label="有效标志">
                <template slot="header"> 有效标志 </template>
                <template slot-scope="scope">
                  <!--@change="change_EnabledMark()"-->
                  <el-switch
                    v-model="scope.row.enabledMark"
                    required
                    :active-value="1"
                    :inactive-value="0"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="50">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    class="SHZY-table-delBtn"
                    @click="
                      handleDelQmsBaseSamplingplandetailEntityList(scope.$index)
                    "
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div
              class="table-actions"
              @click="addHandleQmsBaseSamplingplandetailEntityList()"
            >
              <el-button type="text" icon="el-icon-plus">新增</el-button>
              <!--this.validationOK = true;-->
            </div>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading"
        >确定</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import restAPI from "@/api/q1/basedata/samplingPlan";
import Enumerable from "linq";
import is from "is_js";
import { getDictionaryDataSelector } from "@/api/systemData/dictionary";
import { getDataInterfaceRes } from "@/api/systemData/dataInterface";
export default {
  components: {},
  props: [],
  data() {
    var validatePass = (rule, value, callback) => {
      if (!value || value.trim().length == 0) {
        callback(new Error("请输入抽样方案名称"));
      } else {
        callback();
      }
    };
    return {
      btnLoading: false,
      loading: false,
      visible: false,
      dataForm: {
        id: "",
        name: undefined,
        enabledMark: 1,
        creatorUserId: undefined,
        creatorTime: undefined,
        lastModifyUserId: undefined,
        lastModifyTime: undefined,
        qmsBaseSamplingplandetailList: [],
      },
      rules: {
        name: [
          {
            required: true,
            validator: validatePass,
            message: "请输入抽样方案名称",
            trigger: '"blur"',
          },
        ],
      },
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    checkRule() {
      for (
        let i = 0;
        i < this.dataForm.qmsBaseSamplingplandetailList.length;
        i++
      ) {
        const fe = this.dataForm.qmsBaseSamplingplandetailList[i];
        fe.isOk = true;
        if (is.undefined(fe.lowerLimit)) {
          fe.lowerLimitDesc = "批量下限不能为空！";
          fe.isOk = false;
          this.$message.error(fe.lowerLimitDesc);
        }
        if (is.undefined(fe.upperLimit)) {
          fe.upperLimitDesc = "批量上限不能为空！";
          fe.isOk = false;
          this.$message.error(fe.upperLimitDesc);
        }
        if (is.not.number(parseInt(fe.lowerLimit))) {
          fe.lowerLimitDesc = "请输入的数字！";
          fe.isOk = false;
          this.$message.error(fe.lowerLimitDesc);
        }
        if (is.not.number(parseInt(fe.upperLimit))) {
          fe.upperLimitDesc = "请输入的数字！";
          fe.isOk = false;
          this.$message.error(fe.upperLimitDesc);
        }
        if (parseInt(fe.lowerLimit) <= 0) {
          fe.lowerLimitDesc = "批量下限不能小于0！";
          fe.isOk = false;
          this.$message.error(fe.lowerLimitDesc);
        }
        if (parseInt(fe.upperLimit) <= parseInt(fe.lowerLimit)) {
          fe.lowerLimitDesc = "批量上限不能小于批量下限！";
          fe.isOk = false;
          this.$message.error(fe.lowerLimitDesc);
        }

        if (is.not.number(parseInt(fe.rejectionQty))) {
          fe.rejectionQtyDesc = "请输入的数字！";
          fe.isOk = false;
          this.$message.error(fe.rejectionQtyDesc);
        }
        if (parseInt(fe.rejectionQty) < 0) {
          fe.rejectionQtyDesc = "拒收数不能小于0！";
          fe.isOk = false;
          this.$message.error(fe.rejectionQtyDesc);
        }
        if (is.not.number(parseInt(fe.receivedQty))) {
          fe.receivedQtyDesc = "请输入的数字！";
          fe.isOk = false;
          this.$message.error(fe.receivedQtyDesc);
        }
        if (parseInt(fe.receivedQty) < 0) {
          fe.receivedQtyDesc = "接收数不能小于0！";
          fe.isOk = false;
          this.$message.error();
        }
        if (is.not.number(parseInt(fe.sampleQty))) {
          fe.sampleQtyDesc = "请输入的数字！";
          fe.isOk = false;
          this.$message.error(fe.sampleQtyDesc);
        }
        if (fe.sampleQty < 0) {
          fe.sampleQtyDesc = "样本数量不能小于0！";
          fe.isOk = false;
          this.$message.error(fe.sampleQtyDesc);
        }
        if (parseInt(fe.sampleQty) > parseInt(fe.upperLimit)) { 
          fe.sampleQtyDesc = "样本数量不能大于上限数量！";
          fe.isOk = false;
          this.$message.error(fe.sampleQtyDesc);
        }
        if ((parseInt(fe.receivedQty) + parseInt(fe.rejectionQty)) > parseInt(fe.sampleQty)) { 
          fe.receivedQtyDesc = "接收数和拒收数不能大于样本数量";
          fe.isOk = false;
          this.$message.error(fe.receivedQtyDesc);
        }

        if (i > 0) {
          let pre = this.dataForm.qmsBaseSamplingplandetailList[i - 1];

          if (parseInt(fe.lowerLimit) <= parseInt(pre.upperLimit)) {
            fe.lowerLimitDesc = `批量下限(${fe.lowerLimit})不能小于(${pre.upperLimit})！`;
            fe.isOk = false;
            this.$message.error(fe.lowerLimitDesc);
          }
        }
      }

      let isOk = Enumerable.from(
        this.dataForm.qmsBaseSamplingplandetailList
      ).all((a) => a.isOk);

      return isOk;
    },
    qmsBaseSamplingplandetailExist() {
      let isOk = true;
      for (
        let i = 0;
        i < this.dataForm.qmsBaseSamplingplandetailList.length;
        i++
      ) {
        const e = this.dataForm.qmsBaseSamplingplandetailList[i];
        if (!e.lowerLimit) {
          this.$message({
            message: "批量下限不能为空",
            type: "error",
            duration: 1000,
          });
          isOk = false;
          break;
        }
        if (!e.upperLimit) {
          this.$message({
            message: "批量上限不能为空",
            type: "error",
            duration: 1000,
          });
          isOk = false;
          break;
        }
        if (!e.sampleQty) {
          this.$message({
            message: "样本数量不能为空",
            type: "error",
            duration: 1000,
          });
          isOk = false;
          break;
        }
        if (!e.receivedQty) {
          this.$message({
            message: "接收数不能为空",
            type: "error",
            duration: 1000,
          });
          isOk = false;
          break;
        }
        if (!e.rejectionQty) {
          this.$message({
            message: "拒收数不能为空",
            type: "error",
            duration: 1000,
          });
          isOk = false;
          break;
        }
      }
      return isOk;
    },
    goBack() {
      this.$emit("refresh");
    },
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        this.dataForm.qmsBaseSamplingplandetailList = [];
        if (this.dataForm.id) {
          restAPI.getInfo(this.dataForm.id).then((res) => {
            this.dataForm = res.data;
          });
        }
      });
      this.$store.commit("generator/UPDATE_RELATION_DATA", {});
    },
    dataFormSubmit() {
      let isOk = this.checkRule();
      if (!isOk) {
        //this.$message.error("拒收数不能小于0！");
        return;
      }

      this.$refs["elForm"].validate((valid) => {
        // 校验不通过
        if (!valid || !this.qmsBaseSamplingplandetailExist()) return;

        if (this.dataForm.qmsBaseSamplingplandetailList.length == 0) {
          this.$message.error("请添加抽样规则!");
          return;
        }

        this.btnLoading = true;

        // 新增操作
        if (!this.dataForm.id) {
          restAPI
            .create(this.dataForm)
            .then((res) => {
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.btnLoading = false;
                  (this.visible = false), this.$emit("refresh", true);
                },
              });
            })
            .catch((res) => {
              this.btnLoading = false;
            });

          return;
        }

        // 更新操作
        restAPI
          .update(this.dataForm.id, this.dataForm)
          .then((res) => {
            this.$message({
              message: res.msg,
              type: "success",
              duration: 1000,
              onClose: () => {
                this.btnLoading = false;
                this.visible = false;
                this.$emit("refresh", true);
              },
            });
          })
          .catch((res) => {
            this.btnLoading = false;
          });
      });
    },
    addHandleQmsBaseSamplingplandetailEntityList() {
      // if (this.dataForm.qmsBaseSamplingplandetailList.length > 0)
      // {
      //     let isOk = this.checkRule();
      //     if (!isOk)
      //     {
      //         //this.$message.error("拒收数不能小于0！");
      //         return;
      //     }
      // }

      let item = {
        lowerLimit: undefined,
        lowerLimitDesc: undefined,
        upperLimit: undefined,
        upperLimitDesc: undefined,
        sampleQty: 0,
        sampleQtyDesc: undefined,
        receivedQty: 0,
        receivedQtyDesc: undefined,
        rejectionQty: 0,
        rejectionQtyDesc: undefined,
        enabledMark: 1,
        enabledMarkDesc: undefined,
        isOk: false,
      };
      this.dataForm.qmsBaseSamplingplandetailList.push(item);
    },
    handleDelQmsBaseSamplingplandetailEntityList(index) {
      this.dataForm.qmsBaseSamplingplandetailList.splice(index, 1);
    },
  },
};
</script>
